package 知识点复习.异步回调.综合实例.泡茶喝;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiFunction;

public class DrinkTea {
    public static final int SLEEP_GAP = 3000;    //等待3秒

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //任务1：洗水壶->烧开水
        CompletableFuture<Boolean> hotJob = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":洗好水壶");
            System.out.println(Thread.currentThread().getName() + ":烧开水");
            //线程睡眠一段时间，代表烧水中
            try {
                Thread.sleep(SLEEP_GAP);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + ":水开了");
            return true;
        });
        //任务2：洗茶壶->洗茶杯->拿茶叶
        CompletableFuture<Boolean> washJob = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":洗茶壶");
            System.out.println(Thread.currentThread().getName() + ":洗茶杯");
            System.out.println(Thread.currentThread().getName() + ":拿茶叶");
            //线程睡眠一段时间，代表清洗中
            try {
                Thread.sleep(SLEEP_GAP);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + ":洗完了");
            return true;
        });
        //任务3：任务1和任务2完成后执行泡茶
        CompletableFuture<String> drinkJob = hotJob.thenCombine(washJob, new BiFunction<Boolean, Boolean, String>() {
            @Override
            public String apply(Boolean hotOK, Boolean washOK) {
                if (hotOK && washOK) {
                    System.out.println(Thread.currentThread().getName() + ":泡茶喝，茶喝完");
                    return "茶喝完了";
                }
                return "没有喝到茶";
            }
        });
        //等待任务3执行结果
        System.out.println(Thread.currentThread().getName() + ":" + drinkJob.get());

    }
}
